package com.inspectortime.mail.mailer;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;


/**
 * This implementation is a bit corny, but it was added to support our current development process,
 * allowing developers to easily configure their apps to send emails by passing in an external 
 * properties file containing any necessary javaMail properties
 *  
 * The motivation for this was to allow us to send emails from our local machines via 
 * gmail's smtp server, which requires a bunch of additional settings than a normal localhost sendmail
 * would
 * 
 * Oh, also, you can deactivate the mailer to NOT send emails by setting the property 
 * value 'sender.active' to false
 * 
 * @author bones
 *
 */
public abstract class AbstractPropertyLoadingMailerImpl implements Mailer {

	protected static Log log = LogFactory.getLog(AbstractPropertyLoadingMailerImpl.class);
    
    protected JavaMailSenderImpl mailSender;
    protected boolean isActive = true;
    
    public AbstractPropertyLoadingMailerImpl(Properties props) {
    	
    	if (props.containsKey("sender.active")) {
    		String activeProp = (String) props.getProperty("sender.active");
    		if (activeProp.equals("false")) {
    			this.isActive = false;
    		}
    	}
    	
    	mailSender = new JavaMailSenderImpl();
    	mailSender.setHost(props.getProperty("host"));
    	mailSender.setPort(Integer.parseInt(props.getProperty("port")));
    	
    	if (props.containsKey("protocol")) {
    		mailSender.setProtocol(props.getProperty("protocol"));
    	}
    	if (props.containsKey("username")) {
    		mailSender.setUsername(props.getProperty("username"));
    	}
    	if (props.containsKey("password")) {
    		mailSender.setPassword(props.getProperty("password"));
    	}

    	Properties mailProps = new Properties();
    	if (props.containsKey("mail.smtps.auth")) {
    		mailProps.put("mail.smtps.auth", props.getProperty("mail.smtps.auth"));
    	}
    	if (props.containsKey("mail.smtps.starttls.enable")) {
    		mailProps.put("mail.smtps.starttls.enable", props.getProperty("mail.smtps.starttls.enable"));
    	}
    	if (props.containsKey("mail.smtps.debug")) {
    		mailProps.put("mail.smtps.debug", props.getProperty("mail.smtps.debug"));
    	}
    	if (!mailProps.isEmpty()) {
    		mailSender.setJavaMailProperties(mailProps);
    	}
    }
    
    /**
     * Override this method to differentiate between html mail and simple mail
     */
    public void sendMail(MailMessage mailMsg) {
   		prepareMessageAndSend(mailMsg);
    }
    
    
    /**
     * Override this message to differentiate between Simple mail format 
     * and HTML mail format
     * 
     * @param mailMsg
     */
    protected abstract void prepareMessageAndSend(MailMessage mailMsg);



    
}
